package com.soshalboard.controller;

import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.soshalboard.persistence.domain.Session;
import com.soshalboard.persistence.domain.User;
import com.soshalboard.persistence.domain.WishList;
import com.soshalboard.remote.SessionManager;
import com.soshalboard.remote.interfaces.APIInterface;
import java.net.URLDecoder;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Inject
    APIInterface api;
    @Inject
    SessionManager sessionManager;
    Gson gson = new Gson();

	@RequestMapping(value = "/{session_id}/wishlist/{friend_user_id}", method = RequestMethod.GET)
    @ResponseBody
	public ResponseEntity<String> findFriendsWishList(
			@PathVariable("session_id") final String sessionId,
            @RequestParam(value = "page", required = false, defaultValue = "0") Integer pageNo,
            @RequestParam(value = "size", required = false, defaultValue = "10") Integer pageSize,
			@PathVariable("friend_user_id") final Integer friendUserId) {
		
	    ResponseEntity<String> responseEntity = null;
	    
	    Session session = checkSession(sessionId);
	    
	    if (null == session) 
	        return new ResponseEntity<String>("Not Authorised", HttpStatus.UNAUTHORIZED);
	    
	    if (null == friendUserId) {
	        return new ResponseEntity<String>("Wrong Parameters", HttpStatus.BAD_REQUEST);
	    }
	    	
	    List<WishList> wishList = api.getWishListUsingFbId(friendUserId, pageNo, pageSize);
	    
	    if(wishList != null) {
	        responseEntity = new ResponseEntity<String>(gson.toJson(wishList), HttpStatus.OK);
	    } else {
	        responseEntity = new ResponseEntity<String>("Object Not Found", HttpStatus.NOT_FOUND);
	    }
	    
	    return responseEntity;
	}	
	
    @RequestMapping(value = "/{session_id}/wishlist", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> findWishList(
            @PathVariable("session_id") final String sessionId,
            @RequestParam(value = "page", required = false, defaultValue = "0") Integer pageNo,
            @RequestParam(value = "size", required = false, defaultValue = "10") Integer pageSize) {
        ResponseEntity<String> responseEntity = null;

        Session session = checkSession(sessionId);

        if (null == session) {
            return new ResponseEntity<String>("Not Authorised", HttpStatus.UNAUTHORIZED);
        }

        List<WishList> wishList = api.getWishList(session.getUserId(), pageNo, pageSize);

        if (wishList != null) {
            responseEntity = new ResponseEntity<String>(gson.toJson(wishList), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<String>("Object Not Found", HttpStatus.NOT_FOUND);
        }

        return responseEntity;
    }

    @RequestMapping(value = "/{session_id}/wishlist", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> createOrUpdateWishList(@PathVariable("session_id") final String sessionId,
            @RequestBody String json) {
        ResponseEntity<String> responseEntity = null;

        Session session = checkSession(sessionId);

        if (null == session) {
            return new ResponseEntity<String>("Not Authorised", HttpStatus.UNAUTHORIZED);
        }

        Integer userId = session.getUserId();

        String result = "";
        WishList wishList = null;
        try {
            result = URLDecoder.decode(json, "UTF-8");
            String[] parts = result.split("=");
            wishList = gson.fromJson(parts[0], WishList.class);
        } catch (UnsupportedEncodingException e) {
            return responseEntity = new ResponseEntity<String>("Couldn't read POST data", HttpStatus.BAD_REQUEST);
        }

        if (wishList != null) {
            wishList.getUser().setId(userId);
            api.createOrUpdateWishList(wishList);
            responseEntity = new ResponseEntity<String>(gson.toJson(wishList), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<String>("Object Not Found", HttpStatus.NOT_FOUND);
        }

        return responseEntity;
    }   

    @RequestMapping(value = "/{session_id}/updatewish", method = RequestMethod.PUT)
    @ResponseBody
    public ResponseEntity<String> updateWishList(@PathVariable("session_id") final String sessionId,
            @RequestBody String json) {
        ResponseEntity<String> responseEntity = null;

        responseEntity = createOrUpdateWishList(sessionId, json);

        return responseEntity;
    }   

    
    
    @RequestMapping(value = "/{session_id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> findUser(@PathVariable("session_id") final String sessionId) {
        ResponseEntity<String> responseEntity = null;

        Session userSession = sessionManager.getSessionMap().get(sessionId);

        User user = api.getUser(userSession.getUserId());
        if (user != null) {
            responseEntity = new ResponseEntity<String>(gson.toJson(user), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<String>("Object Not Found", HttpStatus.NOT_FOUND);
        }

        return responseEntity;
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> createOrUpdateUser(
            @RequestBody String json) {

        ResponseEntity<String> responseEntity = null;

        String result = "";
        User user = null;
        try {
            result = URLDecoder.decode(json, "UTF-8");
            String[] parts = result.split("=");
            user = gson.fromJson(parts[0], User.class);
        } catch (UnsupportedEncodingException e) {
            return responseEntity = new ResponseEntity<String>("Couldn't read POST data", HttpStatus.BAD_REQUEST);
        }


        User registeredUser = api.createOrUpdateUser(user);

        Session session = api.getSession(registeredUser.getId());

        if (null == session) {
            String sessionId = UUID.randomUUID().toString();
            session = new Session();
            session.setUserId(registeredUser.getId());
            session.setSessionId(sessionId);

            api.saveSession(session);
        }

        sessionManager.setSession(session.getSessionId(), session);

        if (user != null) {
            responseEntity = new ResponseEntity<String>("{\"sessionId\":\"" + session.getSessionId() + "\"}", HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<String>("Object Not Found", HttpStatus.NOT_FOUND);
        }

        return responseEntity;
    }

    public Session checkSession(String sessionId) {
        if (sessionManager.getSessionMap().containsKey(sessionId)) {
            return sessionManager.getSessionMap().get(sessionId);
        } else {
            Session session = api.getSession(sessionId);
            return session;
        }
    }
}